<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="报表标题" prop="reportTitle">
        <el-input
          v-model="queryParams.reportTitle"
          placeholder="标题关键词"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="统计周期" prop="reportPeriod">
        <el-select v-model="queryParams.reportPeriod" placeholder="选择周期" clearable style="width: 120px">
          <el-option label="日报" value="daily"></el-option>
          <el-option label="周报" value="weekly"></el-option>
          <el-option label="月报" value="monthly"></el-option>
          <el-option label="自定义" value="custom"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报表格式" prop="reportFormat">
        <el-select v-model="queryParams.reportFormat" placeholder="文件格式" clearable style="width: 100px">
          <el-option label="PDF" value="pdf"></el-option>
          <el-option label="Excel" value="excel"></el-option>
          <el-option label="HTML" value="html"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生成状态" prop="generationStatus">
        <el-select v-model="queryParams.generationStatus" placeholder="状态" clearable style="width: 120px">
          <el-option label="生成中" value="generating"></el-option>
          <el-option label="成功" value="success"></el-option>
          <el-option label="失败" value="failed"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生成时间" prop="generationStartTime">
        <el-date-picker clearable
          v-model="queryParams.generationStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期"
          style="width: 150px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="自动生成" prop="autoGenerated">
        <el-select v-model="queryParams.autoGenerated" placeholder="生成方式" clearable style="width: 100px">
          <el-option label="自动" value="1"></el-option>
          <el-option label="手动" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生成者" prop="generatedBy">
        <el-input
          v-model="queryParams.generatedBy"
          placeholder="生成者"
          clearable
          style="width: 120px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:reportGenerationLog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:reportGenerationLog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:reportGenerationLog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:reportGenerationLog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="reportGenerationLogList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      class="common-table"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="ID" align="center" prop="generationId" width="80" />
      <el-table-column label="报表标题" align="center" prop="reportTitle" min-width="200" show-overflow-tooltip />
      <el-table-column label="周期" align="center" prop="reportPeriod" width="80">
        <template slot-scope="scope">
          <el-tag :type="getPeriodTagType(scope.row.reportPeriod)" size="mini">
            {{ getPeriodLabel(scope.row.reportPeriod) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="统计时间" align="center" width="180">
        <template slot-scope="scope">
          <div style="font-size: 12px;">
            <div>{{ parseTime(scope.row.reportStartDate, '{y}-{m}-{d}') }}</div>
            <div style="color: #909399;">{{ parseTime(scope.row.reportEndDate, '{y}-{m}-{d}') }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" align="center" prop="reportFileSize" width="100">
        <template slot-scope="scope">
          <span>{{ formatFileSize(scope.row.reportFileSize) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="格式" align="center" prop="reportFormat" width="80">
        <template slot-scope="scope">
          <el-tag :type="getFormatTagType(scope.row.reportFormat)" size="mini">
            {{ scope.row.reportFormat && scope.row.reportFormat.toUpperCase() }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生成状态" align="center" prop="generationStatus" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.generationStatus)" size="mini">
            {{ getStatusLabel(scope.row.generationStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="生成时间" align="center" width="160">
        <template slot-scope="scope">
          <div style="font-size: 12px;">
            <div>{{ parseTime(scope.row.generationStartTime, '{y}-{m}-{d} {h}:{i}') }}</div>
            <div v-if="scope.row.generationEndTime" style="color: #909399;">
              {{ parseTime(scope.row.generationEndTime, '{h}:{i}:{s}') }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="耗时" align="center" prop="generationDuration" width="80">
        <template slot-scope="scope">
          <span>{{ formatDuration(scope.row.generationDuration) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下载" align="center" width="80">
        <template slot-scope="scope">
          <div style="font-size: 12px;">
            <div>{{ scope.row.downloadCount || 0 }}次</div>
            <div v-if="scope.row.lastDownloadTime" style="color: #909399;">
              {{ parseTime(scope.row.lastDownloadTime, '{m}-{d}') }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="生成方式" align="center" prop="autoGenerated" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.autoGenerated"
            active-value="1"
            inactive-value="0"
            active-text="自动"
            inactive-text="手动"
            disabled
          />
        </template>
      </el-table-column>
      <el-table-column label="生成者" align="center" prop="generatedBy" width="100" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="140" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.generationStatus === 'success'"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            style="color: #67c23a;"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:reportGenerationLog:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:reportGenerationLog:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报表生成记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <!-- 基本信息 -->
          <el-col :span="24">
            <el-divider content-position="left">基本信息</el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板ID" prop="templateId">
              <el-input-number v-model="form.templateId" :min="1" :precision="0" style="width: 100%" placeholder="模板ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报表标题" prop="reportTitle">
              <el-input v-model="form.reportTitle" placeholder="报表标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统计周期" prop="reportPeriod">
              <el-select v-model="form.reportPeriod" placeholder="选择统计周期" style="width: 100%">
                <el-option label="日报" value="daily"></el-option>
                <el-option label="周报" value="weekly"></el-option>
                <el-option label="月报" value="monthly"></el-option>
                <el-option label="自定义" value="custom"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报表格式" prop="reportFormat">
              <el-select v-model="form.reportFormat" placeholder="选择报表格式" style="width: 100%">
                <el-option label="PDF" value="pdf"></el-option>
                <el-option label="Excel" value="excel"></el-option>
                <el-option label="HTML" value="html"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <!-- 统计时间范围 -->
          <el-col :span="24">
            <el-divider content-position="left">统计时间范围</el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="reportStartDate">
              <el-date-picker clearable style="width: 100%"
                v-model="form.reportStartDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="reportEndDate">
              <el-date-picker clearable style="width: 100%"
                v-model="form.reportEndDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          
          <!-- 文件信息 -->
          <el-col :span="24">
            <el-divider content-position="left">文件信息</el-divider>
          </el-col>
          <el-col :span="24">
            <el-form-item label="文件路径" prop="reportFilePath">
              <el-input v-model="form.reportFilePath" type="textarea" :rows="2" placeholder="报表文件存储路径" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件大小(字节)" prop="reportFileSize">
              <el-input-number v-model="form.reportFileSize" :min="0" :precision="0" style="width: 100%" placeholder="文件大小" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成状态" prop="generationStatus">
              <el-select v-model="form.generationStatus" placeholder="选择生成状态" style="width: 100%">
                <el-option label="生成中" value="generating"></el-option>
                <el-option label="成功" value="success"></el-option>
                <el-option label="失败" value="failed"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <!-- 生成信息 -->
          <el-col :span="24">
            <el-divider content-position="left">生成信息</el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成开始时间" prop="generationStartTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.generationStartTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成结束时间" prop="generationEndTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.generationEndTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成耗时(秒)" prop="generationDuration">
              <el-input-number v-model="form.generationDuration" :min="0" :precision="0" style="width: 100%" placeholder="耗时秒数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成者" prop="generatedBy">
              <el-input v-model="form.generatedBy" placeholder="生成者" />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.generationStatus === 'failed'">
            <el-form-item label="错误信息" prop="errorMessage">
              <el-input v-model="form.errorMessage" type="textarea" :rows="3" placeholder="错误详细信息" />
            </el-form-item>
          </el-col>
          
          <!-- 下载统计 -->
          <el-col :span="24">
            <el-divider content-position="left">下载统计</el-divider>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下载次数" prop="downloadCount">
              <el-input-number v-model="form.downloadCount" :min="0" :precision="0" style="width: 100%" placeholder="下载次数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最后下载时间" prop="lastDownloadTime">
              <el-date-picker clearable style="width: 100%"
                v-model="form.lastDownloadTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择下载时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生成方式" prop="autoGenerated">
              <el-switch
                v-model="form.autoGenerated"
                active-value="1"
                inactive-value="0"
                active-text="自动生成"
                inactive-text="手动生成"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReportGenerationLog, getReportGenerationLog, delReportGenerationLog, addReportGenerationLog, updateReportGenerationLog } from "@/api/system/reportGenerationLog";

export default {
  name: "ReportGenerationLog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报表生成记录表格数据
      reportGenerationLogList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateId: null,
        reportTitle: null,
        reportPeriod: null,
        reportStartDate: null,
        reportEndDate: null,
        reportFilePath: null,
        reportFileSize: null,
        reportFormat: null,
        generationStatus: null,
        generationStartTime: null,
        generationEndTime: null,
        generationDuration: null,
        errorMessage: null,
        downloadCount: null,
        lastDownloadTime: null,
        autoGenerated: null,
        generatedBy: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateId: [
          { required: true, message: "模板ID不能为空", trigger: "blur" }
        ],
        reportTitle: [
          { required: true, message: "报表标题不能为空", trigger: "blur" }
        ],
        reportPeriod: [
          { required: true, message: "统计周期不能为空", trigger: "blur" }
        ],
        reportStartDate: [
          { required: true, message: "报表开始日期不能为空", trigger: "blur" }
        ],
        reportEndDate: [
          { required: true, message: "报表结束日期不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询报表生成记录列表 */
    getList() {
      this.loading = true;
      listReportGenerationLog(this.queryParams).then(response => {
        this.reportGenerationLogList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        generationId: null,
        templateId: null,
        reportTitle: null,
        reportPeriod: null,
        reportStartDate: null,
        reportEndDate: null,
        reportFilePath: null,
        reportFileSize: null,
        reportFormat: null,
        generationStatus: null,
        generationStartTime: null,
        generationEndTime: null,
        generationDuration: null,
        errorMessage: null,
        downloadCount: null,
        lastDownloadTime: null,
        autoGenerated: null,
        generatedBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.generationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报表生成记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const generationId = row.generationId || this.ids
      getReportGenerationLog(generationId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报表生成记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.generationId != null) {
            updateReportGenerationLog(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReportGenerationLog(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const generationIds = row.generationId || this.ids;
      this.$modal.confirm('是否确认删除报表生成记录编号为"' + generationIds + '"的数据项？').then(function() {
        return delReportGenerationLog(generationIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/reportGenerationLog/export', {
        ...this.queryParams
      }, `reportGenerationLog_${new Date().getTime()}.xlsx`)
    },
    /** 下载报表文件 */
    handleDownload(row) {
      if (row.reportFilePath) {
        // 实际下载逻辑
        window.open(row.reportFilePath, '_blank');
        this.$modal.msgSuccess('开始下载报表文件');
      } else {
        this.$modal.msgError('报表文件路径不存在');
      }
    },
    /** 获取周期标签类型 */
    getPeriodTagType(period) {
      const typeMap = {
        'daily': 'primary',
        'weekly': 'success',
        'monthly': 'warning',
        'custom': 'info'
      };
      return typeMap[period] || '';
    },
    /** 获取周期显示标签 */
    getPeriodLabel(period) {
      const labelMap = {
        'daily': '日报',
        'weekly': '周报',
        'monthly': '月报',
        'custom': '自定义'
      };
      return labelMap[period] || period;
    },
    /** 获取格式标签类型 */
    getFormatTagType(format) {
      const typeMap = {
        'pdf': 'danger',
        'excel': 'success',
        'html': 'warning'
      };
      return typeMap[format] || '';
    },
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      const typeMap = {
        'generating': 'warning',
        'success': 'success',
        'failed': 'danger'
      };
      return typeMap[status] || '';
    },
    /** 获取状态显示标签 */
    getStatusLabel(status) {
      const labelMap = {
        'generating': '生成中',
        'success': '成功',
        'failed': '失败'
      };
      return labelMap[status] || status;
    },
    /** 格式化文件大小 */
    formatFileSize(size) {
      if (!size || size === 0) return '-';
      const units = ['B', 'KB', 'MB', 'GB'];
      let index = 0;
      let fileSize = size;
      
      while (fileSize >= 1024 && index < units.length - 1) {
        fileSize /= 1024;
        index++;
      }
      
      return `${fileSize.toFixed(index > 0 ? 1 : 0)}${units[index]}`;
    },
    /** 格式化耗时 */
    formatDuration(duration) {
      if (!duration || duration === 0) return '-';
      if (duration < 60) return `${duration}秒`;
      if (duration < 3600) return `${Math.floor(duration / 60)}分${duration % 60}秒`;
      const hours = Math.floor(duration / 3600);
      const minutes = Math.floor((duration % 3600) / 60);
      const seconds = duration % 60;
      return `${hours}时${minutes}分${seconds}秒`;
    }
  }
};
</script>

<style scoped>
/* 优化表格样式 */
.common-table {
  font-size: 13px;
}

.common-table .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

/* 优化数值显示 */
.common-table .el-table__cell {
  padding: 8px 0;
}

/* 标签样式 */
.el-tag {
  font-weight: 500;
}

/* 开关样式 */
.el-switch {
  transform: scale(0.8);
}

/* 表单优化 */
.el-form-item {
  margin-bottom: 18px;
}

.el-divider {
  margin: 15px 0;
}

.el-divider__text {
  font-weight: 600;
  color: #409eff;
}

/* 搜索表单优化 */
.el-form--inline .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

/* 数字输入框优化 */
.el-input-number {
  width: 100%;
}

.el-input-number .el-input__inner {
  text-align: center;
}

/* 多行显示优化 */
.multi-line-cell {
  line-height: 1.4;
}

.multi-line-cell > div:first-child {
  font-weight: 500;
}

.multi-line-cell > div:last-child {
  font-size: 11px;
  color: #909399;
}

/* 操作按钮优化 */
.el-button--text {
  padding: 2px 4px;
  margin: 0 2px;
}

/* 下载按钮特殊样式 */
.download-btn {
  color: #67c23a !important;
  font-weight: 500;
}

.download-btn:hover {
  color: #529b2e !important;
}
</style>
